package com.bigfans.searchservice.service.impl;

import com.bigfans.framework.es.ElasticTemplate;
import com.bigfans.framework.es.request.SearchCriteria;
import com.bigfans.framework.es.request.SearchResult;
import com.bigfans.framework.model.FTSPageBean;
import com.bigfans.framework.utils.StringHelper;
import com.bigfans.searchservice.document.convertor.BrandDocumentConverter;
import com.bigfans.searchservice.document.convertor.CategoryDocumentConverter;
import com.bigfans.searchservice.model.Brand;
import com.bigfans.searchservice.model.Category;
import com.bigfans.searchservice.schema.mapping.BrandMapping;
import com.bigfans.searchservice.schema.mapping.CategoryMapping;
import com.bigfans.searchservice.service.CategoryService;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.PrefixQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 商品类别服务类
 * 
 * @author lichong
 *
 */
@Service(CategoryServiceImpl.BEAN_NAME)
public class CategoryServiceImpl implements CategoryService {

	public static final String BEAN_NAME = "categoryService";

	@Autowired
	private ElasticTemplate elasticTemplate;

	public Category getById(String catId) {
		Category cat = elasticTemplate.getById(CategoryMapping.INDEX, CategoryMapping.TYPE, catId, new CategoryDocumentConverter());
		return cat;
	}

	public FTSPageBean<Category> search(String keyword , int start , int pagesize) throws Exception {
		PrefixQueryBuilder nameQuery = QueryBuilders.prefixQuery(CategoryMapping.FIELD_NAME, keyword);
		SearchCriteria searchCriteria = new SearchCriteria(nameQuery);
		searchCriteria.setIndex(CategoryMapping.INDEX);
		searchCriteria.setType(CategoryMapping.TYPE);
		searchCriteria.setFrom(start);
		searchCriteria.setSize(pagesize);

		SearchResult<Category> result = elasticTemplate.search(searchCriteria, new CategoryDocumentConverter());
		List<Category> data = result.getData();
		FTSPageBean<Category> pageBean = new FTSPageBean<>(data, result.getTotHitis());
		return pageBean;
	}
}
